package com.dataseek.iot.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dataseek.iot.sys.entity.Factory;
import com.dataseek.iot.sys.mapper.FactoryMapper;
import com.dataseek.iot.sys.service.FactoryService;
import com.dataseek.iot.sys.vo.FactoryVo;
import com.dataseek.iot.toolikit.common.enums.RspStatusEnum;
import com.dataseek.iot.toolkit.tenant.config.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class FactoryServiceImpl extends ServiceImpl<FactoryMapper, Factory> implements FactoryService {


    @Autowired
    private FactoryMapper factoryMapper;

    @Override
    public FactoryVo queryAction(String factoryName, String open, Integer num, Integer size) {

        FactoryVo deptVo = new FactoryVo();
        QueryWrapper<Factory> qw = new QueryWrapper<>();
        if (factoryName != null && !factoryName.isEmpty()) {
            qw.like("factory_name", factoryName);
        }
        if (open != null && !open.isEmpty()) {
            qw.eq("open", open);
        }
        IPage<Factory> page = new Page<>(num, size);
        List<Factory> mapList = factoryMapper.selectPage(page, qw).getRecords();
        deptVo.setPage(num);
        deptVo.setSize(size);
        deptVo.setTotal(page.getTotal());
        deptVo.setList(mapList);
        return deptVo;
    }

    @Override
    public Integer insertAction(Factory factory) {
        String tenantCode = DynamicDataSourceContextHolder.getDataSourceKey();
        int resultCode = 0;
        QueryWrapper<Factory> qw = new QueryWrapper<>();
        qw.eq("factory_name", factory.getFactoryName()).or().eq("factory_code", factory.getFactoryCode());
        Integer count = factoryMapper.selectCount(qw);
        if (count == 0) {
            factory.setTenantCode(tenantCode);
            if (factory.getCreateBy() == null) {
                factory.setCreateBy("");
                factory.setUpdateBy("");
            }
            this.saveOrUpdate(factory);
        } else {
            resultCode = RspStatusEnum.FAIL.getCode();
        }
        return resultCode;

    }

    @Override
    public Integer updateAction(Factory factory) {
        int resultCode = factoryMapper.updateById(factory);
        return resultCode;
    }

    @Override
    public Integer deleteAction(List<Integer> ids) {
        int resultCode = factoryMapper.deleteBatchIds(ids);
        return resultCode;
    }

}
